﻿using Adnc.Application.Shared.Dtos;
using Adnc.Application.Shared.Services;
using Adnc.Infra.IRepositories;
using Adnc.Shared.Consts;
using Adnc.Shared.RpcServices.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using WYT.Pro.Application.Contracts.Dtos.Group;
using WYT.Pro.Application.Contracts.Dtos.Product;
using WYT.Pro.Application.Contracts.Services;
using WYT.Pro.Repository.Entites;

namespace WYT.Pro.Application.Services
{
    /// <summary>
    /// 商品服务
    /// </summary>
    public class ProductGroupAppService : AbstractAppService, IProductGroupAppService
    {
        private readonly IEfRepository<GoodsGroups> _goodsGroupRepository;

        private readonly IEfRepository<GoodsGroupDetails> _groupGoodsRepository;

        private readonly IEfRepository<GoodsPrice> _groupPriceRepository;

        private readonly IEfRepository<Goods> _goodsRepository;

        private readonly IEfRepository<GoodsSize> _goodsSizeRepository;

        private readonly IEfRepository<GoodsReview> _goodsReviewRepository;

        private readonly IUserRpcService _userRpcService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="goodsGroupRepository"></param>
        /// <param name="groupGoodsRepository"></param>
        /// <param name="groupPriceRepository"></param>
        /// <param name="goodsRepository"></param>
        /// <param name="goodsSizeRepository"></param>
        /// <param name="goodsReviewRepository"></param>
        /// <param name="userRpcService"></param>
        public ProductGroupAppService(
                    IEfRepository<GoodsGroups> goodsGroupRepository,
                    IEfRepository<GoodsGroupDetails> groupGoodsRepository,
                    IEfRepository<GoodsPrice> groupPriceRepository,
                    IEfRepository<Goods> goodsRepository,
                    IEfRepository<GoodsSize> goodsSizeRepository,
                    IEfRepository<GoodsReview> goodsReviewRepository,
                    IUserRpcService userRpcService)
        {
            _goodsGroupRepository = goodsGroupRepository;
            _goodsRepository = goodsRepository;
            _groupGoodsRepository = groupGoodsRepository;
            _groupPriceRepository = groupPriceRepository;
            _userRpcService = userRpcService;
            _goodsSizeRepository = goodsSizeRepository;
            _goodsReviewRepository = goodsReviewRepository;
        }

        /// <summary>
        /// 获取分组
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<AppSrvResult<List<GroupDto>>> GetProductGroup(GroupSearchDto input)
        {
            List<GoodsGroups> groups;
            if (input.Type != 0)
                groups = await _goodsGroupRepository.Where(c => c.Type == input.Type).OrderBy(x => x.Sort).ToListAsync();
            else
                groups = await _goodsGroupRepository.GetAll().ToListAsync();

            if (input.Language.Equals(LanguageConsts.ZH))
                return groups.Select(c => new GroupDto()
                {
                    Id = c.Id,
                    Name = c.Name,
                    Banner = c.Banner
                }).ToList();
            else
                return groups.Select(c => new GroupDto()
                {
                    Id = c.Id,
                    Name = c.UighurName,
                    Banner = c.UighurBanner
                }).ToList();
        }

        /// <summary>
        /// 商品分组查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<AppSrvResult<PageModelDto<ProductListDto>>> GetProductbyList(GroupProductPagedSearchDto input)
        {
            var userGradeResponse = await _userRpcService.GetUserGrade();
            if (!userGradeResponse.IsSuccessStatusCode)
                throw new Exception("服务异常");
            var grade = userGradeResponse.Content;                               

            Boolean IsZh = input.Language.Equals(LanguageConsts.ZH);

            var group = await _goodsGroupRepository.FindAsync(input.GroupID);
            if (group == null)
                return Problem(null, "参数错误");

            string sql1 = $@"SELECT
                        COUNT(*) num
                        FROM
	                        pro_GoodGroupDetails gd
	                        JOIN pro_Goods g ON gd.GoodsID = g.Id AND g.State = 0 AND (g.PutawayTime IS NULL OR g.PutawayTime < @date) AND (g.OffLoadingTime IS NULL OR g.OffLoadingTime > @date)
	                        JOIN pro_Size gs ON g.Id = gs.GoodsID AND gs.IsDefalut = 1 and gs.State = 0
	                        JOIN pro_Price gp on gp.SizeID = gs.Id and UserLevel = @grade
	                        where gd.GroupID = @GroupID";

            string sql2 = $@"SELECT
	                        g.Id,
	                        g.Name,
	                        g.UighurName,
	                        gs.Id as SizeId,
	                        g.SurfacePlot,
	                        g.UighurSurfacePlot,
	                        g.Tag,
                            g.UighurTag,
	                        gs.Price as OriginalPrice,
	                        gp.Price as CurrentPrice,
	                        g.IsThirdParties,
                            g.IsThirdCoupons,
                            gs.ThirdCommission,
                            g.IsForeign
                        FROM
	                        pro_GoodGroupDetails gd
	                        JOIN pro_Goods g ON gd.GoodsID = g.Id AND g.State = 0 AND (g.PutawayTime IS NULL OR g.PutawayTime < @date) AND (g.OffLoadingTime IS NULL OR g.OffLoadingTime > @date)
	                        JOIN pro_Size gs ON g.Id = gs.GoodsID AND gs.IsDefalut = 1 and gs.State = 0
	                        JOIN pro_Price gp on gp.SizeID = gs.Id and UserLevel = @grade
	                        where gd.GroupID = @GroupID
                            order by gd.Sort desc
                            LIMIT @skip,@take";

            var count = (await _goodsRepository.QueryAsync<int>(sql1, new {grade,input.GroupID, date = DateTime.Now })).FirstOrDefault();
            var data = await _goodsRepository.QueryAsync(sql2, new { grade, input.GroupID, skip= (input.PageIndex - 1) * input.PageSize,take = input.PageSize ,date = DateTime.Now});

            if (data == null || data.Count() == 0)
                return new PageModelDto<ProductListDto>(input, new List<ProductListDto>(), count);

            List<ProductListDto> baseinfor = new List<ProductListDto>();
            //自营产品的封面使用规格图
            foreach (var item in data)
            {
                baseinfor.Add(new ProductListDto
                {
                    Id = item.Id,
                    Name = IsZh ? item.Name : item.UighurName,
                    SizeId = item.SizeId,
                    SurfacePlot = IsZh ? item.SurfacePlot : item.UighurSurfacePlot,
                    OriginalPrice = item.OriginalPrice,
                    CurrentPrice = item.CurrentPrice,
                    IsThirdParties = item.IsThirdParties,
                    IsForeign = item.IsForeign,
                    PriceDiff = item.IsThirdCoupons ? item.ThirdCommission : item.OriginalPrice - item.CurrentPrice,
                    Tag = JsonSerializer.Deserialize<String[]>(IsZh ? item.Tag : item.UighurTag)
                });
            }

            return new PageModelDto<ProductListDto>(input, baseinfor, count);
        }
    }
}
